/**
 * @class Ext.app.PhieuNhapKhoPanel
 * @extends Ext.panel.Panel
 */
Ext.define('Ext.app.PhieuNhapKhoPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.phieuNhapKhoPanel',
    requires: [
        'Ext.app.DanhSachMatHangLookup'
    ],

    initComponent: function () {
        Ext.apply(this, {
            autoScroll: true,
            border: true,
            layout: 'border',
            titleAlign: 'center',
            items: [
                {
                    region: 'north',
                    xtype: 'form',
                    layout: 'hbox',
                    bodyPadding: 5,
                    bodyStyle: 'background:#ECECEC',
                    items: [{
                        xtype:'fieldset',
                        title: translations.get("HOME.TU_KHO"),
                        defaultType: 'textfield',
                        items: [
                            {
                                fieldLabel: translations.get("HOME.TEN_KHO"),
                                labelWidth: 70,
                                maxLength: 100,
                                width: 400,
                                margin: '5 5 5 5',
                                anchor: '-5',
                                afterLabelTextTpl: required,
                                allowBlank: false,
                                blankText: translations.get("HOME.BLANK_TEXT"),
                                name: 'whName'
                            },
                            {
                                fieldLabel: translations.get("HOME.DIA_CHI"),
                                labelWidth: 70,
                                maxLength: 200,
                                width: 400,
                                margin: '5 5 5 5',
                                anchor: '-5',
                                afterLabelTextTpl: required,
                                allowBlank: false,
                                blankText: translations.get("HOME.BLANK_TEXT"),
                                name: 'whAddress'
                            },
                            {
                                fieldLabel: translations.get("HOME.PHONE"),
                                labelWidth: 70,
                                maxLength: 25,
                                width: 400,
                                margin: '5 5 5 5',
                                anchor: '-5',
                                name: 'whPhone'
                            }
                        ]
                    },{
                        xtype:'fieldset',
                        title: translations.get("HOME.DEN_KHO"),
                        defaultType: 'textfield',
                        margin: '0 0 0 10',
                        items: [
                            {
                                fieldLabel: translations.get("HOME.TEN_KHO"),
                                xtype: 'combobox',
                                store: {
                                    fields: ['type', 'name'],
                                    data: [
                                        {"type": "CHINH_PHAM", "name": translations.get("HOME.KHO_CHINH_PHAM")},
                                        {"type": "THU_PHAM", "name": translations.get("HOME.KHO_THU_PHAM")},
                                        {"type": "PHE_PHAM", "name": translations.get("HOME.KHO_PHE_PHAM")}
                                    ]
                                },
                                displayField: 'name',
                                valueField: 'type',
                                value: 'CHINH_PHAM',
                                labelWidth: 70,
                                maxLength: 100,
                                width: 300,
                                margin: '5 5 5 5',
                                anchor: '-5',
                                afterLabelTextTpl: required,
                                editable: false,
                                allowBlank: false,
                                blankText: translations.get("HOME.BLANK_TEXT"),
                                name: 'toWhType'
                            }
                        ]
                    }]
                },
                {
                    region: 'center',
                    xtype: 'cell-editing',
                    columnLines: true,
                    viewConfig: {
                        markDirty: false
                    },
                    store: {
                        fields: ['stt', 'prodPK', 'prodCode', 'tenMH', 'soKg', 'soMet', 'soKgm', 'donGiaNhap', 'thanhTien']
                    },
                    columns: [{ 
                        text: translations.get("HOME.STT"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'stt',
                        width: 50
                    },{
                        text: translations.get("HOME.MA_HANG"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'prodCode',
                        width: 150
                    },{
                        text: translations.get("HOME.PRODUCT_NAME_FOR_SELL"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'tenMH',
                        flex: 1,
                        summaryRenderer: function(value, summaryData, dataIndex) {
                            return "T\u1ed5ng c\u1ed9ng";
                        }
                    },{
                        text: translations.get("HOME.SO_KG"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'soKg',
                        align: 'right',
                        width: 80,
                        editor: new Ext.form.field.Number({
                            hideTrigger: true,
                            fieldStyle: 'text-align:right',
                            minValue: 0,
                            listeners: {
                                change: function(field, newValue, oldValue, eOpts) {
                                    var grid = field.up("cell-editing");
                                    var records = grid.getSelectionModel().getSelection();
                                    if(records.length == 1) {
                                        var soMet = records[0].get("soMet");
                                        if(soMet != null && soMet > 0) {
                                            records[0].set("soKgm", newValue/soMet);
                                        }
                                        else {
                                            records[0].set("soKgm", 0);
                                        }
                                    }
                                    var donGiaNhap = records[0].get("donGiaNhap");
                                    if(donGiaNhap != null) {
                                        records[0].set("thanhTien", donGiaNhap*newValue);
                                    }
                                }
                            }
                        }),
                        summaryType: 'sum',
                        renderer: function(value) {
                            return formatNumber(value);
                        }
                    },{
                        text: translations.get("HOME.SO_MET"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'soMet',
                        width: 80,
                        align: 'right',
                        editor: new Ext.form.field.Number({
                            hideTrigger: true,
                            fieldStyle: 'text-align:right',
                            minValue: 0,
                            listeners: {
                                change: function(field, newValue, oldValue, eOpts) {
                                    var grid = field.up("cell-editing");
                                    var records = grid.getSelectionModel().getSelection();
                                    if(records.length == 1) {
                                        var soKg = records[0].get("soKg");
                                        if(soKg != null && newValue > 0) {
                                            records[0].set("soKgm", (soKg/newValue));
                                        }
                                        else {
                                            records[0].set("soKgm", 0);
                                        }
                                    }
                                }
                            }
                        }),
                        summaryType: 'sum',
                        renderer: function(value) {
                            return formatNumber(value);
                        }
                    },{
                        text: translations.get("HOME.SO_KG_MET"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'soKgm',
                        align: 'right',
                        width: 80,/*
                        editor: new Ext.form.field.Number({
                            hideTrigger: true,
                            fieldStyle: 'text-align:right',
                            minValue: 0
                        }),*/
                        renderer: function(value) {
                            return formatNumber(value);
                        }
                    },{
                        text: translations.get("HOME.DON_GIA_NHAP"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'donGiaNhap',
                        align: 'right',
                        width: 150,
                        editor: new Ext.form.field.Number({
                            allowBlank: false,
                            hideTrigger: true,
                            allowDecimals: false,
                            fieldStyle: 'text-align:right',
                            minValue: 0,
                            listeners: {
                                change: function(field, newValue, oldValue, eOpts) {
                                    var grid = field.up("cell-editing");
                                    var records = grid.getSelectionModel().getSelection();
                                    if(records.length == 1) {
                                        var soKg = records[0].get("soKg");
                                        if(soKg != null) {
                                            records[0].set("thanhTien", soKg*newValue);
                                        }
                                    }
                                }
                            }
                        }),
                        renderer: function(value) {
                            return formatInteger(value);
                        }
                    },{
                        text: translations.get("HOME.THANH_TIEN"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'thanhTien',
                        width: 150,
                        align: 'right',
                        summaryType: 'sum',
                        renderer: function(value) {
                            return formatInteger(value);
                        }
                    }],
                    tbar: [
                        {
                            icon: 'images/add.png',
                            handler: function(button) {
                                var win = Ext.create('widget.dsMatHangLookup', {title: translations.get("HOME.CHON_MAT_HANG")});
                                win.setOpener(button.up('cell-editing'));
                                win.show();
                            }
                        },
                        '-',
                        {
                            text: translations.get("HOME.SAVE"),
                            icon: 'images/disk_blue.png',
                            handler: function(button) {
                                var panel = button.up('phieuNhapKhoPanel');
                                var form = panel.down('form');
                                if(!form.isValid()) {
                                    return;
                                }
                                var grid = button.up('cell-editing');
                                grid.cellEditing.completeEdit();
                                var newRecords = grid.getStore().getNewRecords();
                                var iLength = newRecords.length;
                                if(iLength == 0) {
                                    Ext.MessageBox.alert('', translations.get("HOME.NHAP_MAT_HANG"));
                                    return;
                                }
                                if(!panel.isValid(grid.getStore())) {
                                    return;
                                }
                                var records = [];
                                for(var i=0;i<iLength; i++) {
                                    var r = newRecords[i];
                                    records.push({
                                        stt: r.get("stt"),
                                        prodPK: r.get("prodPK"),
                                        soKg: r.get("soKg"),
                                        soMet: r.get("soMet"),
                                        donGiaNhap: r.get("donGiaNhap")
                                    });
                                }
                                var whName = form.down('[name=whName]').getValue();
                                var whAddress = form.down('[name=whAddress]').getValue();
                                var whPhone = form.down('[name=whPhone]').getValue();
                                var toWhType = form.down('[name=toWhType]').getValue();
                                var param = {
                                    whName: whName,
                                    whAddress: whAddress,
                                    whPhone: whPhone,
                                    toWhType: toWhType,
                                    records: Ext.JSON.encode(records)
                                };
                                Ext.getBody().mask(translations.get("HOME.PLEASE_WAIT"));
                                Ext.Ajax.request({
                                    url: 'LuuPhieuNhapKho.jsp',
                                    params: param,
                                    method: 'POST',
                                    success: function(response, opts) {
                                        Ext.getBody().unmask();
                                        var obj = Ext.decode(response.responseText);
                                        if(!obj.success) {
                                            showErrorMsg(obj.msg);
                                        }
                                        else {
                                            displayPanel({
                                                xtype: 'danhSachPhieuNhapKhoPanel',
                                                title: translations.get("HOME.PHIEU_NHAP_KHO_TITLE")
                                            });
                                        }
                                    },
                                    failure: function(response, opts) {
                                        Ext.getBody().unmask();
                                        alert('server-side failure with status code ' + response.status);
                                    }
                                });
                            }
                        }
                    ],
                    features: [{
                        ftype: 'summary',
                        dock: 'bottom'
                    }],
                    onSelectRecord: function(record) {
                        this.addRow({
                            prodPK: record.prodPK,
                            prodCode: record.code,
                            tenMH: record.nameForSell
                        }, 3);
                    }
                }
            ]            
        });
        this.callParent(arguments);
    },
    
    isNullOrEmpty: function(value) {
        return (value == null || value == "");
    },

    isValid: function(store) {
        var iLength = store.getCount();
        for(var i=0; i<iLength; i++) {
            var record = store.getAt(i);
            if(this.isNullOrEmpty(record.get("prodPK"))) {
                Ext.MessageBox.alert('', translations.get("HOME.NHAP_MAT_HANG"));
                return false;
            }
            else if(this.isNullOrEmpty(record.get("donGiaNhap"))) {
                Ext.MessageBox.alert('', translations.get("HOME.NHAP_DON_GIA"));
                return false;
            }
        }
        return true;
    }
});
